global data_folder_final "W:\intimate\data"
global log_folder "W:\intimate\dofiles\logs"
global result_folder "W:\intimate\results"


import sas using "D:\c55\custom-made\u1067_al3\u1067_al3_vanhempi_lapsi.sas7bdat", clear
count if isa_aiti==""

*keep biological parent and children 
keep if (isa_aiti=="1" | isa_aiti=="2")

gen byc=substr(syntykk_lapsi, 1,4)

destring byc, replace 


sort shnro_v byc

bysort shnro_v: gen child_id=_n

sort shnro_v byc


* shnro_v mother or father id; shnro_l child_id 
duplicates report shnro_l shnro_v
duplicates report shnro_l


preserve 
* keep only mother 
keep if isa_aiti=="2"
duplicates drop shnro_l, force 


keep shnro_l shnro_v byc 

rename shnro_l shnro_sec
rename shnro_v shnro_first 
rename byc byc_sec 

save "$data_folder_final\fir_sec_gen_id_link_mother.dta", replace 

restore 



* keep only father
keep if isa_aiti=="1"
duplicates drop shnro_l, force 


keep shnro_l shnro_v byc 

rename shnro_l shnro_sec
rename shnro_v shnro_first

rename byc byc_sec 

save "$data_folder_final\fir_sec_gen_id_link_father.dta", replace 


// pull mother and father educ 

use "$data_folder_final\fir_sec_gen_id_link_mother.dta", replace 
gen shnro=shnro_first

merge m:1 shnro using "D:\ready-made\FLEED_TOTAL\2016\fleed_kokonais_2010.dta", keepusing (ututku)
drop if _merge==2 


destring ututku, replace 
g educ = floor(ututku/100000)
replace educ = 0 if missing(ututku)

rename educ mom_educ 

drop shnro ututku _merge 

save "$data_folder_final\fir_sec_gen_id_link_mother.dta", replace 




use "$data_folder_final\fir_sec_gen_id_link_father.dta", replace 
gen shnro=shnro_first

merge m:1 shnro using "D:\ready-made\FLEED_TOTAL\2016\fleed_kokonais_2010.dta", keepusing (ututku)
drop if _merge==2 

destring ututku, replace 
g educ = floor(ututku/100000)
replace educ = 0 if missing(ututku)

rename educ dad_educ 

drop shnro ututku _merge 

save "$data_folder_final\fir_sec_gen_id_link_father.dta", replace 



